package junit.admin;

import com.jfinal.aop.Inject;
import io.jboot.test.MockMvcResult;
import io.jpress.module.article.model.Article;
import io.jpress.module.article.service.ArticleService;
import junit.base.AdminBaseTester;
import org.junit.Assert;
import org.junit.Test;

import java.util.Map;

public class AdminArticleTester extends AdminBaseTester {

    @Inject
    private ArticleService articleService;

    @Test
    public void startArticleTestCases() {

        //用户登录，默认账号 admin 123456
        doLogin();

        //发布文章，及其相关验证
        testPublishArticle();

        //更新文章
        testUpdateArticle();

        //删除文章
        testDeleteArticle();

    }


    /**
     * 测试发布文章
     */
    public void testPublishArticle() {
        Article article = new Article();
        article.setTitle("test title");

        Map<String, Object> paras = buildParas(article, "article");
        MockMvcResult mvcResult = postWithCsrfToken("/admin/article/doWriteSave", paras);
        Assert.assertTrue(mvcResult.getContent().contains("文章内容不能为空"));


        article.setContent("test content");
        paras = buildParas(article, "article");
        mvcResult = postWithCsrfToken("/admin/article/doWriteSave", paras);
        Assert.assertTrue(mvcResult.getContent().contains("请选择文章分类"));

        //传入文章分类ID
        paras.put("category", 1);
        mvcResult = postWithCsrfToken("/admin/article/doWriteSave", paras);

        Assert.assertTrue(mvcResult.getStatus() == 200);
        Assert.assertTrue(mvcResult.getContentAsJSONObject().get("state").equals("ok"));

        Long articleId = mvcResult.getContentAsJSONObject().getLong("id");
        putContainerData("articleId", articleId);

        mvcResult.printResult();
    }


    /**
     * 测试更新文章
     */
    public void testUpdateArticle() {

        Article article = new Article();
        article.setTitle("test title");
        article.setContent("new test content");
        article.setId((Long) getContainerData("articleId"));

        Map<String, Object> paras = buildParas(article, "article");

        //传入文章分类ID
        paras.put("category", 1);
        MockMvcResult mvcResult = postWithCsrfToken("/admin/article/doWriteSave", paras);
        mvcResult.printResult();

        Assert.assertTrue(mvcResult.getStatus() == 200);
        Assert.assertTrue(mvcResult.getContentAsJSONObject().get("state").equals("ok"));

        Long articleId = mvcResult.getContentAsJSONObject().getLong("id");
        putContainerData("articleId", articleId);

        final Article byId = articleService.findById(articleId);
        Assert.assertEquals(byId.getContent(), article.getContent());
    }


    /**
     * 测试删除文章
     */
    public void testDeleteArticle() {
        Long articleId = (Long) getContainerData("articleId");
        MockMvcResult mvcResult = getWithCsrfToken("/admin/article/doDel/" + articleId);
        mvcResult.printResult();

        Assert.assertTrue(mvcResult.getStatus() == 200);
    }


}
